package com.ellricky.tv.ui

import android.content.Intent
import android.content.pm.ActivityInfo
import android.view.View
import com.andr.common.ui.activity.BaseActivity
import com.andr.common.ui.mvp.BasePresenter
import com.andr.common.util.ToastUtil
import com.ellricky.baselib.BaseConstant
import com.ellricky.baselib.cache.LocalCacheUtil
import com.ellricky.baselib.entity.UserBean
import com.ellricky.baselib.entity.UserEntity
import com.ellricky.baselib.http.HttpUtils
import com.ellricky.baselib.util.EAppUtil
import com.ellricky.baselib.util.NewEntityCallback
import com.ellricky.tv.Const
import com.ellricky.tv.util.API_LOGIN
import com.ellricky.tv.R
import com.ellricky.tv.util.checkLoginInput
import com.ellricky.tv.util.TvEntityCallback
import kotlinx.android.synthetic.main.tv_activity_login.*

class TvLoginActivity : BaseActivity<Void, BasePresenter<Void>>() {

    private var fromMain = false

    override fun getContentLayout(): Int {
        return R.layout.tv_activity_login
    }

    override fun initUIView() {

        fromMain = intent.getBooleanExtra("fromMain", false)
        if (fromMain) LocalCacheUtil.removeLocalUser()

        val localUser = LocalCacheUtil.readLocalUser()
        if (localUser != null) {
            jumpMainPage()
            return
        }

        btnLogin.setOnClickListener(this)
    }

    override fun onClickView(v: View?) {
        super.onClickView(v)
        if (v == btnLogin) {
            val mobile = etMobile.text.toString().trim()
            val pwd = etPsd.text.toString().trim()
            if (checkLoginInput(this, mobile, pwd)) {
                login(mobile, pwd)
            }
        }
    }

    private fun login(tel: String, pwd: String) {

        val url = EAppUtil.getETvApiHost()
        val paramMap = mutableMapOf(
            "action" to BaseConstant.ACTION_LOGIN,
            "tel" to tel,
            "pwd" to pwd
        )

        HttpUtils.getInstance().postFrom(url, paramMap, object : NewEntityCallback<UserBean>(this) {

            override fun onSuccess(data: UserBean, msg: String) {
                if (data.U_role == BaseConstant.CARD_TEACHER) {
                    LocalCacheUtil.saveUser(data)
                    jumpMainPage()
                } else {
                    ToastUtil.show(this@TvLoginActivity, "您不是教师 无法登录")
                }
            }
        }, this)
    }

    private fun jumpMainPage() {
        val intent = Intent(this, TvCourseTypeSelectActivity::class.java)

        intent.let {
            startActivity(it)
            finish()
        }
    }

    override fun setOrientation() {
        this.requestedOrientation =
            ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpUtils.getInstance().cancelTag(this)
    }
}